<template>
  <div class="dashboard" style="padding-top: 4em">
    <header-bar
      showMenu
      showLogo
      style="display: flex; justify-content: space-between; width: 100%"
    >
      <div style="display: flex; justify-content: end; flex: 1">
        <el-dropdown style="margin-right: 10px">
          <span class="el-dropdown-link">
            <img src="@/assets/user.png" width="40" alt="" />
            <!-- <el-icon class="el-icon--right">
                  <arrow-down />
              </el-icon> -->
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <!--          <el-dropdown-item>-->
              <!--            <el-text type="info">欢迎您，</el-text>-->
              <!--            <el-text type="primary">{{ currentUser.user_name }}</el-text>-->
              <!--          </el-dropdown-item>-->
              <el-dropdown-item @click="handlerChangePassword()">
                <el-text type="info">修改密码</el-text>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
        <action
          v-if="canLogout"
          :label="t('sidebar.logout')"
          @action="auth.logout"
        />
      </div>
    </header-bar>

    <!--      <el-dropdown style="margin-right: 10px">-->
    <!--          <span class="el-dropdown-link">-->
    <!--            <img src="@/assets/user.png" width="40" alt="" />-->
    <!--            &lt;!&ndash; <el-icon class="el-icon&#45;&#45;right">-->
    <!--                  <arrow-down />-->
    <!--              </el-icon> &ndash;&gt;-->
    <!--          </span>-->
    <!--        <template #dropdown>-->
    <!--          <el-dropdown-menu>-->
    <!--            &lt;!&ndash;          <el-dropdown-item>&ndash;&gt;-->
    <!--            &lt;!&ndash;            <el-text type="info">欢迎您，</el-text>&ndash;&gt;-->
    <!--            &lt;!&ndash;            <el-text type="primary">{{ currentUser.user_name }}</el-text>&ndash;&gt;-->
    <!--            &lt;!&ndash;          </el-dropdown-item>&ndash;&gt;-->
    <!--            <el-dropdown-item @click="handlerChangePassword()">-->
    <!--              <el-text type="info">修改密码</el-text>-->
    <!--            </el-dropdown-item>-->
    <!--          </el-dropdown-menu>-->
    <!--        </template>-->
    <!--      </el-dropdown>-->

    <div id="nav">
      <div class="wrapper">
        <ul>
          <!--          <router-link to="/settings/profile">-->
          <!--            <li :class="{ active: $route.path === '/settings/profile' }">-->
          <!--              {{ t("settings.profileSettings") }}-->
          <!--            </li>-->
          <!--          </router-link>-->
          <router-link to="/settings/shares" v-if="user?.perm.share">
            <li :class="{ active: $route.path === '/settings/shares' }">
              分享详情
            </li>
          </router-link>
          <!--          <router-link to="/settings/global" v-if="user?.perm.admin">-->
          <!--            <li :class="{ active: $route.path === '/settings/global' }">-->
          <!--              {{ t("settings.globalSettings") }}-->
          <!--            </li>-->
          <!--          </router-link>-->
          <!--          <router-link to="/settings/users" v-if="user?.perm.admin">-->
          <!--            <li-->
          <!--              :class="{-->
          <!--                active:-->
          <!--                  $route.path === '/settings/users' || $route.name === 'User',-->
          <!--              }"-->
          <!--            >-->
          <!--              {{ t("settings.userManagement") }}-->
          <!--            </li>-->
          <!--          </router-link>-->
        </ul>
      </div>
    </div>

    <div v-if="loading">
      <h2 class="message delayed">
        <div class="spinner">
          <div class="bounce1"></div>
          <div class="bounce2"></div>
          <div class="bounce3"></div>
        </div>
        <span>{{ t("files.loading") }}</span>
      </h2>
    </div>

    <router-view></router-view>
  </div>
  <el-dialog v-model="dialogFormVisible" title="修改密码" width="500">
    <el-form ref="formRef" :model="form" :rules="formRules">
      <!--      <el-form-item-->
      <!--        label="旧密码"-->
      <!--        :label-width="formLabelWidth"-->
      <!--        prop="user_old_password"-->
      <!--      >-->
      <!--        <el-input-->
      <!--          v-model="form.user_old_password"-->
      <!--          autocomplete="off"-->
      <!--          show-password-->
      <!--        />-->
      <!--      </el-form-item>-->
      <el-form-item
        label="新密码"
        :label-width="formLabelWidth"
        prop="user_password"
      >
        <el-input
          v-model="form.user_password"
          autocomplete="off"
          show-password
        />
      </el-form-item>
      <el-form-item
        label="确认新密码"
        :label-width="formLabelWidth"
        prop="confirm_password"
      >
        <el-input
          v-model="form.confirm_password"
          autocomplete="off"
          show-password
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button
          type="primary"
          @click="changePasswordFunc"
          style="background-color: #1749d7"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { useAuthStore } from "@/stores/auth";
import { useLayoutStore } from "@/stores/layout";
import HeaderBar from "@/components/header/HeaderBar.vue";
import { computed, inject, reactive, ref } from "vue";
import { useI18n } from "vue-i18n";
import * as auth from "@/utils/auth.ts";
import Action from "@/components/header/Action.vue";
import { loginPage, noAuth } from "@/utils/constants.ts";
import { ElMessage } from "element-plus";
import { users as usersApi } from "@/api";

const { t } = useI18n();

const authStore = useAuthStore();
const layoutStore = useLayoutStore();

const user = computed(() => authStore.user);
const loading = computed(() => layoutStore.loading);
const canLogout = computed(() => {
  return !noAuth && loginPage;
});


const dialogFormVisible = ref(false);
const formLabelWidth = "120px";

const form = reactive({
  user_old_password: "",
  user_password: "",
  confirm_password: "",
});

const formRef = ref();
const formRules = {
  // user_old_password: [
  //   { required: true, message: "请输入旧密码", trigger: "blur" },
  // ],
  user_password: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 6, max: 10, message: "密码长度需在6-10位之间", trigger: "blur" },
  ],
  confirm_password: [
    { required: true, message: "请输入确认新密码", trigger: "blur" },
    {
      validator: (_: any, value: string, callback: any) => {
        if (value !== form.user_password) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
};

function handlerChangePassword() {
  dialogFormVisible.value = true;
}

function changePasswordFunc() {
  formRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      if (form.user_password.trim() !== form.confirm_password.trim()) {
        ElMessage.error("两次输入的新密码不一致");
        return;
      }
      // ChangePassword(sm3(form.user_old_password), sm3(form.user_password)).then(res => {
      //   if (res.data.code === 0) {
      //     ElMessage({
      //       message: res.data.info,
      //       type: 'success',
      //     })
      //     resetForm()
      //     dialogFormVisible.value = false
      //   } else {
      //     ElMessage.error(res.data.info)
      //   }
      // })
      try {
        const data = {
          ...authStore.user,
          id: authStore?.user?.id,
          password: form.user_password,
        };
        await usersApi.update(data, ["password"]);
        authStore.updateUser(data);
        ElMessage({
          message: "修改密码成功",
          type: "success",
        });
        dialogFormVisible.value = false;
        // $showSuccess(t("settings.passwordUpdated"));
      } catch (e: any) {
        $showError(e);
      } finally {
        // password.value = passwordConf.value = "";
      }
    }
  });
}
const $showError = inject<IToastError>("$showError")!;
</script>
